<template>
	<view class="page bg-fff">
		<view class="header flex top-20">
			<button 
				class="weekBtn clearBtn flex font12" 
				@click="clickPreviousWeek"
			>
				<up-icon name="arrow-left" size="12" color="#8A8A8A"></up-icon>
				<tetx class="left-5">上一周</tetx>
			</button>

			<text class="fontBold font14">{{ currentWeek.start }} - {{ currentWeek.end }}</text>

			<button 
				class="weekBtn clearBtn flex font12" 
				:class="{'col-grey': isNextWeekDisabled}"
				@click="handleNextWeek"
			>
				<text class="right-5">下一周</text>
				<up-icon name="arrow-right" size="12" :color="isNextWeekDisabled ? '#8A8A8A' : '#333333'"></up-icon>
			</button>
		</view>
		<view class="districts flex" v-if="isAdmin">
			<block v-for="(item,index) in districtList" :key="index">
				<view class="district bg-fff boxShadow text-center" :class="{'active':item.value === activeDistrict.value}" @click="selectDistrict(item)">
					{{ item.name }}
				</view>
			</block>
		</view>
		<view class="table">
			<view class="district-title bg-fff" v-if="isAdmin">{{ activeDistrict.name }}</view>
			<view class="table-header flex bg-theme col-fff">
				<text class="nameWrap txtHidden">楼盘名称</text>
				<view class="numWrap text-center">
					<view>真实来电</view>
					<view class="font12">(个)</view>
				</view>

				<view class="numWrap text-center">
					<view>真实到访</view>
					<view class="font12">(人)</view>
				</view>
				
				<view class="numWrap text-center">
					<view>真实签约</view>
					<view class="font12">(套)</view>
				</view>
			</view>
			<block v-for="(item,index) in dataList" :key="index">
				<view class="table-row flex font13">
					<text class="nameWrap txtHidden">{{ item.product_title }}</text>
					<text class="numWrap text-center">{{ item.buy }}</text>
					<text class="numWrap text-center">{{ item.view }}</text>
					<text class="numWrap text-center">{{ item.sign }}</text>
				</view>
			</block>

			<up-loadmore :status="loadingType" margin-top="30" v-if="dataList.length > 0" />
			
			<up-empty text="暂无数据" marginTop="100" mode="list" v-if="dataList.length === 0 && loadingType === 'nomore'"></up-empty>
		</view>
	</view>
</template>

<script setup>
import { ref, computed } from 'vue';
import { storeToRefs } from 'pinia';
import { useIndexStore, useUserInfoStore } from '@/store/index';
import { onLoad, onReachBottom, onUnload } from '@dcloudio/uni-app';
import { getVisitDataAPIByRole } from '@/common/api/my';

const indexStore = useIndexStore();
const userInfoStore = useUserInfoStore();

let currentDate = ref(new Date());
let currentWeek = ref({});
let districtList = ref([]);
let activeDistrict = ref({});

// 缓存数据
let cacheKeyData = ref({});
let next = ref('');
let loadingType = ref('loadmore');
let dataList = ref([]);

const { userInfo } = storeToRefs(userInfoStore);

// 是否是管理员
const isAdmin = computed(() => {
	return userInfo.value.roles.includes('admin');
})

//是否是区域代表
const isAld = computed(() => {
	return userInfo.value.roles.includes('ald');
})

// 添加计算属性判断是否禁用下一周按钮
const isNextWeekDisabled = computed(() => {
    const today = new Date();
    const nextWeekStart = new Date(currentDate.value);
    nextWeekStart.setDate(nextWeekStart.getDate() + 7);
    
    // 将时间设置为当天的开始（00:00:00）
    today.setHours(0, 0, 0, 0);
    nextWeekStart.setHours(0, 0, 0, 0);
    
    // 如果下一周的开始日期大于今天，则禁用按钮
    return nextWeekStart > today;
});

onLoad(() => {
	initPage()
})

// 触底加载
onReachBottom(async () => {
	await loadData();
})

onUnload(() => {
	cacheKeyData.value = {};
})

// 初始化页面
async function initPage() {
	//不是管理员返回页面
	if(!isAdmin.value && !isAld.value) {
		uni.$u.toast('您没有权限访问此页面');
		setTimeout(() => {
			uni.navigateBack();
		}, 1000)
		return;
	}
	
	await indexStore.getCityFilterMenuParams();
	let areaList = indexStore.filterAreaList;
	//去除不限和周边
	areaList = areaList.filter(item => item.name !== '不限' && item.name !== '周边');
	districtList.value = areaList.map(item => ({name: item.name, value: item.value}));
	activeDistrict.value = districtList.value[0];
	updateWeek()
}

// 更新本周日期
async function updateWeek() {
	currentWeek.value = getWeekRange(currentDate.value)
	let key = `${currentWeek.value.start.replace(/\./g, '-')}${currentWeek.value.end.replace(/\./g, '-')} - ${activeDistrict.value.value}`;
	if(cacheKeyData.value[key]) {
		dataList.value = cacheKeyData.value[key].list;
		next.value = cacheKeyData.value[key].next;
		loadingType.value = cacheKeyData.value[key].loadingType;
		return;
	}
	next.value = '';
	loadingType.value = 'loadmore';
	await loadData();
}

//加载数据
async function loadData() {
	if(loadingType.value === 'nomore' || loadingType.value === 'loading') {
		return;
	}
	loadingType.value = 'loading';
	let key = `${currentWeek.value.start.replace(/\./g, '-')}${currentWeek.value.end.replace(/\./g, '-')} - ${activeDistrict.value.value}`;
	let reqParams = {
		start: currentWeek.value.start.replace(/\./g, '-'),
		end: currentWeek.value.end.replace(/\./g, '-')
	}
	if(isAdmin.value) {
		reqParams.area_code = activeDistrict.value.value;
	}
	try {
		let { status, detail } = await getVisitDataAPIByRole(reqParams);
		if(status !== 0) {
			uni.$u.toast(detail);
			return;
		}
		if(cacheKeyData.value[key]) {
			cacheKeyData.value[key].list.push(...detail.results);
			cacheKeyData.value[key].next = detail.next;
			cacheKeyData.value[key].loadingType = detail.next ? 'loadmore' : 'nomore';
		} else {
			cacheKeyData.value[key] = {
				list: detail.results,
				next: detail.next,
				loadingType: detail.next ? 'loadmore' : 'nomore'
			};
		}
		dataList.value = cacheKeyData.value[key].list;
		next.value = cacheKeyData.value[key].next;
		loadingType.value = cacheKeyData.value[key].loadingType;
	} catch (error) {
		uni.$u.toast('获取数据失败');
	}
}

// 获取本周日期
function getWeekRange(date) {
	let current = new Date(date);
	let firstDay = current.getDate() - current.getDay() + 1;
	let lastDay = firstDay + 6;
	let startDate = new Date(current.setDate(firstDay));
	let endDate = new Date(current.setDate(lastDay));
	return {
		start: formatDate(startDate),
		end: formatDate(endDate)
	};
}

// 格式化日期
function formatDate(date) {
	let year = date.getFullYear();
	let month = (date.getMonth() + 1).toString().padStart(2, '0');
	let day = date.getDate().toString().padStart(2, '0');
	return `${year}.${month}.${day}`;
}

// 上一周
function clickPreviousWeek() {
	let newDate = new Date(currentDate.value);
	newDate.setDate(newDate.getDate() - 7);
	currentDate.value = newDate;
	updateWeek();
}

// 下一周
function handleNextWeek() {
	if (!isNextWeekDisabled.value) {
		clickNextWeek();
	}
}

function clickNextWeek() {
	let newDate = new Date(currentDate.value);
	newDate.setDate(newDate.getDate() + 7);
	currentDate.value = newDate;
	updateWeek();
}

// 选择区域
function selectDistrict(item) {
	activeDistrict.value = item;
	updateWeek();
}

</script>

<style lang="scss" scoped>
.page {
	min-height: 100vh;
	overflow: hidden;
	margin: 0 auto;
	.header {
		justify-content: space-between;
		padding: 10rpx 20rpx;
		.weekBtn{
            margin: 0;
        }
	}
	
	.districts {
		display: grid;
		grid-template-columns: repeat(4, 1fr);
		gap: 20rpx;
		padding: 20rpx;
		.district {
			padding: 10rpx 20rpx;
			border-radius: 10rpx;
		}
		.district.active {
			background-color: $theme-color;
			color: white;
		}
	}
}

.table {
	margin: 28rpx 20rpx;
	border-collapse: collapse;
	.district-title {
		padding: 10rpx 20rpx;
	}
	.nameWrap{
		width: 34vw;
		padding-left: 10rpx;
	}
	.numWrap{
		width: 22vw;
	}
	.table-header,.table-row {
		display: flex;
		justify-content: space-between;
		padding: 16rpx 8rpx;
	}

	.table-row:nth-child(even) {
		background-color: rgba(0,114,53,.15);
	}
}
</style>
